package it.datagraf.formazione.hellostruts.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import it.datagraf.formazione.hellostruts.entity.Competenza;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class CompetenzaDao implements CompetenzaDaoI {
	private SessionFactory sessionFactory;
	/* (non-Javadoc)
	 * @see it.datagraf.formazione.hellostruts.dao.CompentenzaDaoI#saveOrUpdate(it.datagraf.formazione.hellostruts.entity.Competenza)
	 */
	@Override
	public Long saveOrUpdate(Competenza comp) {
//		Long res=comp.getId();
//		if(comp.getId()==null || comp.getId()<0)
//			res= (Long)sessionFactory.getCurrentSession().save(comp);
//		else
//			sessionFactory.getCurrentSession().update(comp);
//		return res;
		System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO");
		sessionFactory.getCurrentSession().save(comp); 

		this.sessionFactory.getCurrentSession().save(comp);
		sessionFactory.getCurrentSession().flush();		
		return comp.getId();
	}
	
	/* (non-Javadoc)
	 * @see it.datagraf.formazione.hellostruts.dao.CompentenzaDaoI#get(java.lang.Long)
	 */
	@Override
	public Competenza get(Long id) {
		return (Competenza)this.sessionFactory.getCurrentSession().get(Competenza.class, id);
	}


	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public List<Competenza> listComps() throws SQLException {
		Session s=sessionFactory.getCurrentSession();
		return s.createQuery("from Competenza").list();
	}

	@Override
	public void removeComp(long id) throws SQLException {
		Competenza comp=get(id);
		this.sessionFactory.getCurrentSession().delete(comp);
	}
	
	public List<Competenza> getRootNodes() {
		List<Competenza> results=new ArrayList<Competenza>();
		results=this.sessionFactory.getCurrentSession().createQuery("From Competenza where parent is null").list();
		return results;
	}
	
	
	

}
